package com.ffcs.ffxtc.utils;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.ffcs.ffxtc.modules.base.domin.entity.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

/**
 * 用户数据工具类
 *
 * @author zhangzhengxing
 */
@Slf4j
public class UserUtils {
    /**
     * 获取用户数据
     *
     * @return
     */
    public static UserInfo getUserInfo() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        UserInfo userInfo = new UserInfo();
        try {
            HttpServletRequest request = requestAttributes.getRequest();
            String token = URLDecoder.decode(request.getHeader("Authorization"), StandardCharsets.UTF_8);
            token = token.split(" ")[1];
            JWT jwt = JWTUtil.parseToken(token);

            String payloadNumber = (String) jwt.getPayload("id");
            userInfo.setId(payloadNumber);
            userInfo.setRealname((String) jwt.getPayload("realname"));
            userInfo.setUserName((String) jwt.getPayload("userName"));
        } catch (Exception e) {
            log.error("token解析用户数据失败:" + e.getMessage());
        }

        if (userInfo.getId() == null) {
            userInfo.setId("0");
            userInfo.setRealname("模拟用户");
        }

        return userInfo;
    }
}
